#!/bin/bash

#   Copyright (C) 2016 Deepin, Inc.
#
#   Author:     Li LongYu <lilongyu@linuxdeepin.com>
#               Peng Hao <penghao@linuxdeepin.com>

#	修改者:		wsgalaxy <wsgalaxy@qq.com> 2018/6/20

#todo: add support for fcitx
APPID="com.tencent.wechat"
WINEID="Deepin-WeChat"
WINEPREFIX="$HOME/.var/app/$APPID/wine/$WINEID"
APPDIR="/app/data/"
APPTAR="files.7z"
FONTTAR="font.tar.xz"
APPEXECMD="c:\\Program Files\\Tencent\\WeChat\\WeChat.exe"
WINEEXE="/usr/lib/deepin-wine/wine"
EXTDIR="/app/ext/"

HelpApp()
{
	echo " Extra Commands:"
	echo " -r/--reset     Reset app to fix errors"
	echo " -e/--remove    Remove deployed app files"
	echo " -h/--help      Show program help info"
}

#在执行应用前需要执行的脚本
PreRun()
{
	#解决无法在中文系统下输入中文
	export LC_ALL="en_US.UTF-8"

	#输入法默认使用IBUS
#	export XMODIFIERS=@im=ibus
	export GTK_IM_MODULE=ibus
	export QT_IM_MODULE=ibus

	#执行EXTDIR目录下各个子目录内的脚本文件
	for _dir in `ls $EXTDIR -F | grep "/$"`
	do
		if [ -f $EXTDIR/$_dir/script.sh ]
		then
			source $EXTDIR/$_dir/script.sh
		fi
	done

#		for _script in `ls $EXTDIR/$_dir`
#		do
#			_file=$EXTDIR/$dir/$_script
#			if [ -f $_file ]
#			then 
#				source $_file
#			fi
#		done
#	done
}


#执行wine应用
CallApp()
{
	PreRun

	WINEPREFIX=$WINEPREFIX WINELOADER=$WINEEXE $WINEEXE "$APPEXECMD"
}
#解压
ExtractApp()
{
	echo "Extraing app"
	mkdir -p "$1"
	#tar xf "$APPDIR/$APPTAR" -C "$1"
	7z x "$APPDIR/$APPTAR" -o"$1"
	tar xf "$APPDIR/$FONTTAR" -C "$1/drive_c/windows/Fonts"
	#echo "Do not delete this file if you do not want to delete your app" > "$1/drive_c/deepin/finished"
	echo "done"
	#mv "$1/drive_c/users/@current_user@" "$1/drive_c/users/$USER"
	#sed -i "s#@current_user@#$USER#" $1/*.reg
}
#部署
DeployApp()
{
	ExtractApp "$WINEPREFIX"
	#echo "$APPVER" > "$WINEPREFIX/PACKAGE_VERSION"
}
#删除
RemoveApp()
{
	rm -rf "$WINEPREFIX"
}
#重置
ResetApp()
{
	echo "Reset $APPID....."
	read -p "*	Are you sure?(Y/N)" ANSWER
	if [ "$ANSWER" = "Y" -o "$ANSWER" = "y" -o -z "$ANSWER" ]; then
		#EvacuateApp
		RemoveApp
		DeployApp
		CallApp
	fi
}
#更新
UpdateApp()
{
	echo "updating ......"
}

#运行
RunApp()
{
 	if [ -d "$WINEPREFIX" ]; then
 		UpdateApp
 	else
 		DeployApp
 	fi
 	CallApp
}

#无参数直接运行
if [ -z $1 ]; then
	RunApp
	exit 0
fi
#有参数
case $1 in
	"-r" | "--reset")
		#重置
		ResetApp
		;;
	"-e" | "--remove")
		#删除
		RemoveApp
		;;
	"-h" | "--help")
		HelpApp
		;;
	*)
		echo "Invalid option: $1"
		echo "Use -h|--help to get help"
		exit 1
		;;
esac

exit 0
